package org.ojudge.ojudgecodesandbox.sandbox.impl;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import lombok.extern.slf4j.Slf4j;
import org.ojudge.ojudgecodesandbox.modal.ExecuteMessage;
import org.ojudge.ojudgecodesandbox.sandbox.template.JavaCodeSandboxTemplate;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Docker中的代码沙箱
 */
@Slf4j
@Component
public class JavaDockerCodeSandbox extends JavaCodeSandboxTemplate {

    private static final long TIME_OUT = 5000;

    private static Boolean FIRST_INIT = false;

    @Override
    public List<ExecuteMessage> runCode(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParent();
        //获取默认的DockerClient
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();


        //拉取镜像
        String image = "openjdk:8-alpine";
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback callback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(callback).awaitCompletion();
            } catch (InterruptedException e) {
                log.error("拉取镜像失败");
                return null;
            }
            FIRST_INIT = false;
            log.info("下载镜像:{}", image);
        }

        //创建容器

        CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));//绑定挂载,用于同步文件内容
        hostConfig.withMemory(100 * 1024 * 1024L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        hostConfig.withReadonlyRootfs(true);
        hostConfig.withSecurityOpts(Arrays.asList("seccomp=安全管理配置字符串"));


        CreateContainerResponse createContainerResponse = createContainerCmd
                .withNetworkDisabled(true)
                .withHostConfig(hostConfig)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withTty(true) //启动之后容器可以一直存在,不会退出
                .exec();
        String containerId = createContainerResponse.getId();
        System.out.println("容器创建成功：" + containerId);

        //启动容器
        dockerClient.startContainerCmd(containerId).exec();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();

        // docker exec exciting_kapitsa java -cp ./app Main 1 3
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch(); // 创建计时器
            String[] inputArgsArray = inputArgs.split(" ");// 把输入参数转换成数组
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);// 创建命令
            long time;
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            log.info("创建执行命令:{}", execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};

            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        log.info("docker exec输出错误结果{}", errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        log.info("docker exec输出结果{}", message[0]);
                    }
                    super.onNext(frame);
                }
            };

            final long[] maxMemory = {0L};

            //获取内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    Long memoryUsage = statistics.getMemoryStats().getUsage();
                    log.info("内存占用{}", memoryUsage);
                    maxMemory[0] = Math.max(maxMemory[0], memoryUsage != null ? memoryUsage : 0L);
                }

                @Override
                public void onStart(Closeable closeable) {
                }

                @Override
                public void onError(Throwable throwable) {
                }

                @Override
                public void onComplete() {
                }

                @Override
                public void close() {
                }
            };
            statsCmd.exec(statisticsResultCallback);

            //运行代码
            try {
                stopWatch.start();
                boolean completion = dockerClient
                        .execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
                if (!completion) {
                    log.error("执行超时");
                    executeMessage.setExitValue(-1);
                    executeMessage.setMessage("代码执行超时");
                    executeMessage.setErrorMessage("代码执行超时");
                    executeMessage.setTime(TIME_OUT);
                    executeMessage.setMemory(0L);
                    executeMessageList.add(executeMessage);
                    continue;
                }
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                log.error("执行错误{}", e.getMessage());
                throw new RuntimeException(e);
            }
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setMessage(message[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            log.info("执行结果{}", executeMessage);
            executeMessageList.add(executeMessage);
        }
        return executeMessageList;
    }
}
